package com.sunday.aomi.ui.product;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.sunday.common.adapter.CommonAdapter;
import com.sunday.common.adapter.RecylerViewHolder;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.PixUtils;
import com.sunday.common.utils.SpannalbeStringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.UIAlertView;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.aomi.R;
import com.sunday.member.entity.product.CollectionProduct;
import com.sunday.member.entity.product.Product;
import com.sunday.member.entity.product.ProductDetail;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/5/31.
 */

public class ProductCollectionActivity extends BaseActivity {


    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collection_list);
        ButterKnife.bind(this);
        title.setText("商品收藏");
        initRecylerView();
        getData();
    }


    private LinearLayoutManager layoutManager;
    private int lastVisibleItem;
    private boolean isCanloadMore;
    private int pagNo = 1;
    private int pageSize = 10;
    private CommonAdapter<CollectionProduct> adapter;
    private List<CollectionProduct> dataSet = new ArrayList<>();

    private void initRecylerView() {
        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new CommonAdapter<CollectionProduct>(mContext, R.layout.layout_collection_item, dataSet) {
            @Override
            public void convert(RecylerViewHolder holder, CollectionProduct product) {
                bind(holder, product);
            }
        };
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());
        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pagNo=1;
                getData();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pagNo = 1;
                getData();
            }
        });

    }

    private void getData() {
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"type", "pageSize", "pageNumber", "nonce"};
        String[] str2 = new String[]{"1", String.valueOf(pageSize), String.valueOf(pagNo), nonce};
        showLoadingDialog(0);
        Call<ResultDO<List<CollectionProduct>>> call = MemberClient.getApiAdapter().getCollection("1", pageSize, pagNo, null, null, nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<List<CollectionProduct>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<CollectionProduct>>> call, Response<ResultDO<List<CollectionProduct>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                ptrFrame.refreshComplete();
                if (response.body().getResult() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    if (pagNo == 1) {
                        dataSet.clear();
                    }
                    if (response.body().getResult().size() == 10) {
                        pagNo++;
                        isCanloadMore = true;
                    } else {
                        isCanloadMore = false;
                    }
                    dataSet.addAll(response.body().getResult());
                    if (dataSet.size() > 0) {
                        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    } else {
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    }

                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                    emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(Call<ResultDO<List<CollectionProduct>>> call, Throwable t) {
                ptrFrame.refreshComplete();
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
                emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
            }
        });
    }

    private void bind(RecylerViewHolder holder, final CollectionProduct product) {
        ImageView imageView = holder.getView(R.id.product_img);
        if (!TextUtils.isEmpty(product.getImage())) {
            Picasso.with(mContext)
                    .load(product.getImage())
                    .error(R.mipmap.ic_default)
                    .resize(150, 150).into(imageView);
        }
        ((TextView) holder.getView(R.id.product_title)).setText(product.getName());
        ((TextView) holder.getView(R.id.price_now)).setText(SpannalbeStringUtils.setTextSizePx("￥", PixUtils.sp2px(mContext, 12)));
        ((TextView) holder.getView(R.id.price_now)).append(SpannalbeStringUtils.setTextSizePx(
                String.valueOf(product.getPrice().setScale(2, RoundingMode.HALF_UP)), PixUtils.sp2px(mContext, 15)));

        ((TextView) holder.getView(R.id.price_old)).setText(String.format("￥%s", product.getMarketPrice().setScale(2, RoundingMode.HALF_UP)));
        ((TextView) holder.getView(R.id.price_old)).getPaint().setFlags(Paint.ANTI_ALIAS_FLAG | Paint.STRIKE_THRU_TEXT_FLAG);
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.total_layout:
                        intent = new Intent(mContext, ProductDetailActivity.class);
                        intent.putExtra("productId", product.getId());
                        startActivity(intent);
                        break;
                    case R.id.btn_delete:
                        final UIAlertView alertView = new UIAlertView(mContext, "温馨提示", "确认删除吗", "取消", "确定");
                        alertView.show();
                        alertView.setClicklistener(new UIAlertView.ClickListenerInterface() {
                            @Override
                            public void doLeft() {
                                alertView.dismiss();
                            }

                            @Override
                            public void doRight() {
                                cancelCollect(product.getId());
                                alertView.dismiss();
                            }
                        });
                        break;
                }
            }
        };
        holder.setOnClickListener(R.id.total_layout, onClickListener);
        holder.setOnClickListener(R.id.btn_delete, onClickListener);

    }


    private void cancelCollect(long productId) {
        String nonce = MD5Utils.random();
        String otherId = String.valueOf(productId);
        String[] str1 = new String[]{"type", "otherId", "nonce"};
        String[] str2 = new String[]{"1", String.valueOf(otherId), nonce};
        showLoadingDialog(0);
        Call<ResultDO> call = MemberClient.getApiAdapter().doCollection("1", otherId, nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext, "已取消收藏");
                    getData();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }


}
